package com.company.oa.announcement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.oa.announcement.dto.FeedbackDTO;
import com.company.oa.announcement.entity.AnnouncementFeedback;
import com.company.oa.announcement.mapper.AnnouncementFeedbackMapper;
import com.company.oa.announcement.service.AnnouncementFeedbackService;
import com.company.oa.common.exception.BusinessException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class AnnouncementFeedbackServiceImpl extends ServiceImpl<AnnouncementFeedbackMapper, AnnouncementFeedback> implements AnnouncementFeedbackService {

    @Override
    public IPage<AnnouncementFeedback> getFeedbackPage(int page, int size, Long announcementId) {
        Page<AnnouncementFeedback> pageParam = new Page<>(page, size);
        return baseMapper.selectFeedbackPage(pageParam, announcementId);
    }

    @Override
    public boolean submitFeedback(FeedbackDTO feedbackDTO, Long userId, String userName) {
        // 检查是否已提交过反馈
        if (hasSubmittedFeedback(feedbackDTO.getAnnouncementId(), userId)) {
            throw new BusinessException("您已提交过反馈");
        }
        
        AnnouncementFeedback feedback = new AnnouncementFeedback();
        feedback.setAnnouncementId(feedbackDTO.getAnnouncementId());
        feedback.setUserId(userId);
        feedback.setUserName(userName);
        feedback.setRating(feedbackDTO.getRating());
        feedback.setComment(feedbackDTO.getComment());
        feedback.setCreateTime(LocalDateTime.now());
        
        return save(feedback);
    }

    @Override
    public Map<String, Object> getFeedbackStats(Long announcementId) {
        return baseMapper.selectFeedbackStats(announcementId);
    }

    @Override
    public boolean hasSubmittedFeedback(Long announcementId, Long userId) {
        LambdaQueryWrapper<AnnouncementFeedback> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AnnouncementFeedback::getAnnouncementId, announcementId)
               .eq(AnnouncementFeedback::getUserId, userId);
        
        return baseMapper.selectCount(wrapper) > 0;
    }
} 